package dapps.web.monitor;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.web.struts2.Struts2Utils;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
import com.opensymphony.xwork2.ActionSupport;

import dapps.entity.monitor.Servicedata;
import dapps.entity.monitor.Servicemain;
import dapps.entity.monitor.Servicepredi;
import dapps.entity.user.Type;
import dapps.service.monitor.MonitorManager;
import dapps.service.user.UserManager;

@SuppressWarnings("serial")
public class ServicexplortAction extends ActionSupport {

	@Autowired
	private MonitorManager mManager;
	@Autowired
	private UserManager uManager;
	
	private Long monitorid;
	private static String monitortitle = "杭州市重点服务业企业监测月度报表";
	private HttpServletRequest request = Struts2Utils.getRequest();
	private static String[] headstrarray = { "序号", "重要程度", "项目名称", "建设内容及规模",
			"总投资（万元）", "总用地（亩）", "农用地（亩）", "其中：耕地、林地（亩）",
			"项目建议书批复文号", "项目可研报告(核准或备案)批复文号", "方案设计或初步设计批复文号",
			"规划选址意见书", "规划用地许可证", "用地预审文号", "责任单位", "备注" };
	private static String[] headargarray = { "序号", "重要程度", "项目名称", "建设内容及规模",
		"总投资（万元）", "总用地（亩）", "农用地（亩）", "其中：耕地、林地（亩）",
		"是否已组件上报市国土局", "市国土局是否已收件", "市国土局是否上报省国土资源厅",
		"省国土资源厅是否已批复", "责任单位", "备注" };
	private static String[] title={"实施项目","预备项目","储备项目","拟争取省留指标项目"};
	private static String[] intarray = { "","一", "二", "三","四", "五","六", "七", "八", "九","十"};
	private static String[] intsarray = { "","（一）", "（二）", "（三）","（四）", "（五）","（六）", "（七）", "（八）", "（九）","（十）"};
	private DecimalFormat nfx = new DecimalFormat("0.#");

	@Override
	public String execute() throws Exception {
		return export();
	}

	public String export() throws Exception {
		Servicemain servicemain = mManager.get(monitorid);
		Servicedata servicedata = mManager.getData(monitorid);
		Servicepredi servicepredi = mManager.getDatapredi(monitorid);
		//printWord(Struts2Utils.getResponse(),1,"");
		exportword();
		return NONE;
	}
	
	private String exportword() throws FileNotFoundException {
		ServletContext application = Struts2Utils.getApplication();
		String filepath =application.getRealPath("/");
		FileInputStream in = new FileInputStream(filepath+"/monitor.doc");
		try {
			HWPFDocument doc = new HWPFDocument(in);
			Range range = doc.getOverallRange();
			int numP = range.numParagraphs(); // 得到range范围的Paragraph的个数
			int m = 0; // 数组下标
			String[] ret = new String[numP];System.out.println(numP);
			int outtablepara = 1;
			/*for (int i = 0; i < numP; ++i) {// 从每一段落中获取文字,每一段是一个回车
				org.apache.poi.hwpf.usermodel.Paragraph p = range.getParagraph(i);
				System.out.println(p.text()+" "+i);
				if (p.isInTable()) {//上一段在table外 ，所以本段为table第一段
					if (outtablepara == 1) {
						outtablepara = 0;
						org.apache.poi.hwpf.usermodel.Table table = range.getTable(p); // 通过第一个在table中的Paragraph来获取整个table
						int numRow = table.numRows();
						if (numRow > 0) {
							for (int j = 0; j < numRow; j++) {// 遍历行
								TableRow tablerow = table.getRow(j); // 获得一行
								int numbercell = tablerow.numCells();
								if(numbercell>0){
									for (int k = 0; k < numbercell; k++) {// 遍历单元格
										TableCell tablexell = tablerow.getCell(k); // 获得单元格
										int p1 = tablexell.numParagraphs(); // 获取单元格中的Paragraph的个数
										String str = "";
										for (int l = 0; l < p1; l++) {
											org.apache.poi.hwpf.usermodel.Paragraph para = tablexell.getParagraph(l);
											str = str + para.text().trim(); // 得到单元格中的内容
											//if(para.text().trim().length()<1) tablexell.insertBefore("d");
										}
										for (int n = m; n < numP;) {
											ret[n] = str; // 将单元格中的内容方入数组元素中
											break;
										}
										
										m++;
									}
								}
							}
						}
					}
				}else{					
					outtablepara = 1;
				}
			}*/
			HttpServletResponse response = Struts2Utils.getResponse();
			OutputStream out = response.getOutputStream();
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String(monitortitle.getBytes("gb2312"), "ISO8859-1") + ".doc");
			response.setContentType("application/msword;charset=UTF-8");
			doc.write(out);
			out.flush();
			out.close();

			//WordExtractor extractor;
			//extractor = new WordExtractor(in);
			//String text = extractor.getText();
			//System.out.println(text);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return NONE;
	}

	public String printWord(HttpServletResponse response,int detaili,
			String title) throws Exception {
		Document document = new Document(PageSize.A4.rotate());
		try {
			// 定义输出位置并把文档对象装入输出对象中
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			RtfWriter2.getInstance(document, outputStream);
			// 打开文档对象
			document.open();
			BaseFont bfChinese = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

			Font titleFont = new Font(bfChinese, 22, Font.BOLD);
			Font contextFont = new Font(bfChinese, 10.5f, Font.NORMAL);
			Font tableheadFont = new Font(bfChinese, 10.5f, Font.BOLD);
			Paragraph ptitle = new Paragraph(title);
			ptitle.setAlignment(Element.ALIGN_CENTER);
			ptitle.setFont(titleFont);
			document.add(ptitle);
			

			// 设置 Table 表格
			Table aTable = new Table(16);
			int width[] = { 3, 3, 8, 8, 5, 5, 5, 5, 7, 7, 7, 7, 7, 7, 6, 5 };
			aTable.setWidths(width);// 设置每列所占比例
			aTable.setWidth(100); // 占页面宽度 90%

			aTable.setAlignment(Element.ALIGN_CENTER);// 居中显示
			aTable.setAlignment(Element.ALIGN_MIDDLE);// 纵向居中显示
			aTable.setAutoFillEmptyCells(true); // 自动填满
			aTable.setBorderWidth(1); // 边框宽度
			aTable.setBorder(2);// 边框

			// 设置表头
			/**
			 * cell.setHeader(true);是将该单元格作为表头信息显示；
			 * cell.setColspan(3);指定了该单元格占3列； 为表格添加表头信息时，要注意的是一旦表头信息添加完了之后， 必须调用
			 * endHeaders()方法，否则当表格跨页后，表头信息不会再显示
			 */

			Cell haderCell = null;			
			
			for (int i = 0; i < headstrarray.length; i++) {
				haderCell = new Cell(new Paragraph(headstrarray[i],tableheadFont));
				if (i < 8 || i > 13) haderCell.setRowspan(2);
				haderCell.setHeader(true);
				haderCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
				haderCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
				aTable.addCell(haderCell);
				if (i == 7) {
					haderCell = new Cell(new Paragraph("项目前期工作进度",tableheadFont));
					haderCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
					haderCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
					haderCell.setColspan(6);
					haderCell.setHeader(true);
					i = 13;
					aTable.addCell(haderCell);
				} else if (i == 15) {
					i = 7;
				} else if (i == 13) {
					i = 15;
				}
			}
			aTable.endHeaders();
			int typerow = 0;int typeprow = 0;
			String tempstr = "";String lasttypepname ="";
/*			if (dataList != null && dataList.size() > 0) {
				
				int lasttid = 0;
				int k = 3;
				
				String lasttypename = "";
				
				Integer sum = new Integer(0);//分类总计
				Integer sump = new Integer(0);//父分类总计
				Integer sumproj = new Integer(0);//总计
				
				Double sumagrarea = new Double(0);Double sumpagrarea = new Double(0);
				Double sumprojagrarea = new Double(0);				
				
				for (int j = 0; j < headstrarray.length; j++) {
					if(j==2){
						Cell cell = new Cell("");
						cell.setColspan(2);
						cell.setHorizontalAlignment(Cell.ALIGN_CENTER);
						aTable.addCell(cell);
						j=j+1;
					}else{						
						aTable.addCell(this.createDocCell(tableheadFont , "c", ""));
					}
					
				}

				for (int i = 0; i < dataList.size(); i++) {
					Proj model = (Proj) dataList.get(i);
					Type modeltype = model.getType();
					if (lasttid != modeltype.getTid()) {
						if (typerow!=0) {// 上一type row									
							insertDocCell(aTable,typerow,2,tableheadFont, lasttypename + "（" + sum + "个项目）");							
							sumproj += sum;sump += sum;
							sum = 0;
							
							insertDocCell(aTable,typerow,6,tableheadFont, nfx.format(sumagrarea));						
							sumprojagrarea += sumagrarea;sumpagrarea += sumagrarea;
							sumagrarea = 0D;

						}
						if(modeltype.getTid()%100==1){  //出现子分类 需要加父分类行
							typeprow = i+k;k++;
							for (int j = 0; j < headstrarray.length; j++) {
								if(j==2){
									Cell cell = new Cell("");
									cell.setColspan(2);
									cell.setHorizontalAlignment(Cell.ALIGN_CENTER);
									aTable.addCell(cell);
									j=j+1;
								}else{
									aTable.addCell(this.createDocCell(tableheadFont , "c", ""));
								}
							}
							sump=0;//sumpinvest=0L;sumparea=0D;
							sumpagrarea=0D;//sumpfarmingarea=0D;
							Type tp = typeManager.getTypeByTid(modeltype.getTid()/100*100);
							lasttypepname = intarray[modeltype.getTid()/100]+ "、" +tp.getName();							
						}
						if(modeltype.getTid()%100==0){ //无子分类时 父分类行赋空 type p row判定是否处在父类下
							if(typeprow!=0){
								insertDocCell(aTable,typeprow,2,tableheadFont,  lasttypepname + "（" + sump + "个项目）");
								insertDocCell(aTable,typeprow,6,tableheadFont, nfx.format(sumpagrarea));
							}
							typeprow = 0;
						}
						
						typerow = i+k;				
						for (int j = 0; j < headstrarray.length; j++) {
							if(j==2){
								Cell cell = new Cell("");
								cell.setColspan(2);
								cell.setHorizontalAlignment(Cell.ALIGN_CENTER);
								aTable.addCell(cell);
								j=j+1;								
							}else{
								aTable.addCell(this.createDocCell(tableheadFont , "c", ""));
							}
							
							
						}
						lasttypename = (modeltype.getTid()%100!=0?intsarray[modeltype.getTid()%100]:intarray[modeltype.getTid() / 100])+ "、" + modeltype.getName();

						k++;
					}

					sumagrarea += (model.getAgrarea() != null) ? model.getAgrarea() : 0;
					sum++;
					
					aTable.addCell(this.createDocCell(contextFont , "c", i + 1));
					aTable.addCell(this.createDocCell(contextFont , "c", (model.getZd() != null && model.getZd() == 1) ? "*": ""));
					aTable.addCell(this.createDocCell(contextFont , "l",  model.getTitle()));
					tempstr = "";
					if (model.getContentlength() != null) tempstr += "长" + model.getContentlength() + "米 ";
					if (model.getContentwidth() != null) tempstr += "，宽" + model.getContentwidth() + "米 ";
					if (model.getContentarea() != null) tempstr += "建筑面积" + model.getContentarea() + "平方米 ";
					if (model.getContent() != null) tempstr += model.getContent();
					aTable.addCell(this.createDocCell(contextFont , "c", tempstr));
					if(model.getType().getId().intValue()==8&&model.getInvest()!=null&&model.getInvest()>0) {
						tempstr = model.getInvest()+"万美元";
						aTable.addCell(this.createDocCell(contextFont , "c", tempstr));
					}else{
						aTable.addCell(this.createDocCell(contextFont , "c",  model.getInvest()));
					}
					aTable.addCell(this.createDocCell(contextFont , "c",  model.getArea()));
					aTable.addCell(this.createDocCell(contextFont , "c",  model.getAgrarea()));
					aTable.addCell(this.createDocCell(contextFont , "c",  model.getFarmingarea()));
					if (detaili == 0) {
						aTable.addCell(this.createDocCell(contextFont , "c",  StringUtils.isNotBlank(model.getJys()) ? "√" : ""));
						aTable.addCell(this.createDocCell(contextFont , "c",  StringUtils.isNotBlank(model.getKy()) ? "√" : ""));
						aTable.addCell(this.createDocCell(contextFont , "c",  StringUtils.isNotBlank(model.getSj()) ? "√" : ""));
						aTable.addCell(this.createDocCell(contextFont , "c",  StringUtils.isNotBlank(model.getXz()) ? "√" : ""));
						aTable.addCell(this.createDocCell(contextFont , "c",  StringUtils.isNotBlank(model.getYdxk()) ? "√" : ""));
						aTable.addCell(this.createDocCell(contextFont , "c",  StringUtils.isNotBlank(model.getYdys()) ? "√" : ""));
					} else {
						aTable.addCell(this.createDocCell(contextFont , "l", model.getJys()));
						aTable.addCell(this.createDocCell(contextFont , "l", model.getKy()));
						aTable.addCell(this.createDocCell(contextFont , "l", model.getSj()));
						aTable.addCell(this.createDocCell(contextFont , "l", model.getXz()));
						aTable.addCell(this.createDocCell(contextFont , "l", model.getYdxk()));
						aTable.addCell(this.createDocCell(contextFont , "l", model.getYdys()));
					}

				aTable.addCell(this.createDocCell(contextFont , "c", model.getDutycomp().getName()));

				tempstr = (model.getBb() != null && model.getBb() == 1) ? "报部": "";
				if (model.getNote() != null) tempstr += model.getNote();
				aTable.addCell(this.createDocCell(contextFont , "c", tempstr));

				lasttid = modeltype.getTid();
			}
			// 最后一个type
			if (typerow != 0) {
				insertDocCell(aTable,typerow,2,tableheadFont, lasttypename + "（" + sum + "个项目）");
				sumproj += sum;			
		
				insertDocCell(aTable,typerow,6,tableheadFont, nfx.format(sumagrarea));						
				sumprojagrarea += sumagrarea;			

			}
			insertDocCell(aTable,2,2,tableheadFont,  "合计（" + sumproj + "个项目）");
			insertDocCell(aTable,2,6,tableheadFont, nfx.format(sumprojagrarea));

		} else {
			this.createDocCell(contextFont , "l",  "查无资料");
		}
*/
			document.add(aTable);
			document.add(new Paragraph("\n")); 
			document.add(new Paragraph(title));
			document.close();
			
			response.addHeader("Content-Disposition","attachment; filename="+ new String(title.getBytes("gb2312"), "ISO8859-1") + ".doc");
			response.setContentType("application/octet-stream");
			response.setContentLength(outputStream.size());
			OutputStream out = response.getOutputStream();
			outputStream.writeTo(out);
			out.flush();
			out.close();
			

		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return NONE;
	}
	
	private Cell createDocCell(Font font,String cellType, Object value) throws BadElementException {
		Cell  cell= new Cell(new Paragraph(value!=null?value.toString():"",font));
		if(cellType.equals("c")){
			cell.setHorizontalAlignment(Cell.ALIGN_CENTER);
		}else{
			cell.setHorizontalAlignment(Cell.ALIGN_LEFT);
		}
		
		cell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
		return cell;
	}
	
	private void insertDocCell(Table table,int x,int y,Font font, Object value) throws BadElementException {		
		Cell c = (Cell) table.getElement(x,y);
		if(c!=null){
			c.addElement(new Paragraph(value!=null?value.toString():"",font));
		}else{
			table.addCell(this.createDocCell(font,"c",value),x,y);
		}
		
	}

	public Long getMonitorid() {
		return monitorid;
	}

	public void setMonitorid(Long monitorid) {
		this.monitorid = monitorid;
	}
	
	

}
